import api from './request';

export interface PostPayload {
  authorId: number;
  title: string;
  content: string;
  categoryId?: number;
}

export interface UpdatePostPayload {
  id: number;
  title: string;
  content: string;
  status: number;
}

export async function createPost(payload: PostPayload) {
  return api.post('/posts', payload);
}

export async function updatePost(payload: UpdatePostPayload) {
  return api.put('/posts', payload);
}

//根据id获取帖子
export async function getPostById(id: number) {
  return api.get(`/posts/${id}`);
}

//根据作者获取帖子
export async function getPostsByAuthorId(authorId: number, pageNum: number = 1, pageSize: number = 10) {
  const res = await api.get(`/posts/author/${authorId}`, { params: { pageNum, pageSize } })
  
  // 兼容老接口和新的后端响应格式
  if (Array.isArray(res.data)) {
    return { list: res.data, total: res.data.length }
  } else if (res.data?.data?.records) {
    // 嵌套的响应格式：res.data.data.records
    return { 
      list: res.data.data.records, 
      total: res.data.data.total,
      pageNum: res.data.data.pageNum,
      pageSize: res.data.data.pageSize,
      totalPages: res.data.data.totalPages
    }
  } else if (res.data?.records) {
    // 直接的响应格式：res.data.records
    return { 
      list: res.data.records, 
      total: res.data.total,
      pageNum: res.data.pageNum,
      pageSize: res.data.pageSize,
      totalPages: res.data.totalPages
    }
  } else if (res.data?.data?.list) {
    return { list: res.data.data.list, total: res.data.data.total }
  } else {
    return { list: [], total: 0 }
  }
}

// 获取所有帖子（分页）
export async function getAllPosts(page: number, size: number) {
  return api.get('/posts', { params: { page, size } });
}

export async function deletePost(id: number) {
  return api.delete(`/posts/${id}`);
}

// 支持关键词和分页的帖子搜索
export async function getPosts(params: {
  keyword?: string
  category?: number
  user?: number
  pageNum?: number
  pageSize?: number
}) {
  const res = await api.get('/posts/search', { params })
  // 兼容不同后端返回结构
  if (Array.isArray(res.data)) {
    return { list: res.data, total: res.data.length }
  } else if (res.data?.data?.records) {
    return { list: res.data.data.records, total: res.data.data.total }
  } else if (res.data?.records) {
    return { list: res.data.records, total: res.data.total }
  } else {
    return { list: [], total: 0 }
  }
}

// 点赞相关接口
// 点赞帖子
export async function likePost(postId: number, userId: number) {
  return api.post(`/posts/${postId}/likes`, null, {
    params: { userId }
  });
}

// 取消点赞
export async function unlikePost(postId: number, userId: number) {
  return api.delete(`/posts/${postId}/likes`, {
    params: { userId }
  });
}

// 查询用户是否点赞了某个帖子
export async function hasLiked(postId: number, userId: number) {
  return api.get(`/posts/${postId}/likes/status`, {
    params: { userId }
  });
}

// 获取帖子点赞数
export async function getLikeCount(postId: number) {
  return api.get(`/posts/${postId}/likes/count`);
}
